package com.nl.controller.sms5g.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.global.GlobalConstants;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.common.util.BaseResult;
import com.nl.controller.common.util.MD5;
import com.nl.controller.sms5g.bean.NewTemplateSyncResp;
import com.nl.controller.sms5g.bean.Rets;
import com.nl.controller.sms5g.bean.Sms5gTemplateInfo;
import com.nl.controller.sms5g.bean.UploadFileInfo;
import com.nl.controller.sms5g.bean.bo.*;
import com.nl.controller.sms5g.bean.po.SignatureInfo;
import com.nl.controller.sms5g.mapper.Sms5gSignatureMapper;
import com.nl.controller.sms5g.mapper.Sms5gTemplateMapper;
import com.nl.controller.sms5g.service.Sms5gTemplateService;
import com.nl.controller.web.global.GlobalConst;
import com.nl.controller.web.mapper.SmsBusiMapper;
import com.nl.controller.web.mapper.SmsTemplateCheckMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @desc 5g多媒体模板同步
 * @return null
 * @author l
 * @date 2021/6/8 19:30
 */
@Service
@Slf4j
public class Sms5GTemplateServiceImpl implements Sms5gTemplateService {

    @Autowired
    private Sms5gSignatureMapper sms5gSignatureMapper;

    @Autowired
    private Sms5gTemplateMapper sms5gTemplateMapper;

    @Autowired
    private SmsBusiMapper smsBusiMapper;

    @Autowired
    private SmsTemplateCheckMapper smsTemplateCheckMapper;
    /**
     * @desc 新增模板同步
     * @param new5gTemplateSyncBo 
     * @return com.nl.controller.common.util.BaseResult
     * @author l
     * @date 2021/6/9 10:32
     */
    @Override
    public BaseResult newTemplateSync(New5gTemplateSyncBo new5gTemplateSyncBo) {
        BaseResult baseResult = BaseResult.newFailInstance();
        CreateMgrSignRelBo createMgrSignRelBo = new CreateMgrSignRelBo();
        String signId = new5gTemplateSyncBo.getSignId();
        String mgrId = new5gTemplateSyncBo.getMgrId();
        createMgrSignRelBo.setMgrId(mgrId);
        createMgrSignRelBo.setSignId(signId);
        createMgrSignRelBo.setTopic(new5gTemplateSyncBo.getTopic());
        //新增5g项目和签名以及主题的关联关系
        sms5gTemplateMapper.createMgrSignRel(createMgrSignRelBo);

        SignatureInfo signatureInfo = sms5gSignatureMapper.qrySignatureInfoById(signId);
        String openAccout = signatureInfo.getOpenAccount();
        String isArrearage = signatureInfo.getIsArrearage();
        //根据签名变更项目开户以及欠费状态
        if("0".equals(openAccout)){
            //签名未开户，项目也置为已开户
            openAccout = "-1";
        }
        smsBusiMapper.updateOpenAccoutIsArrearage(openAccout,isArrearage,mgrId);

        //获取模板帧数
        int length = new5gTemplateSyncBo.getUploadFileOrderBo().size();

        JSONObject req = new JSONObject();
        JSONObject contentJson = new JSONObject();
        JSONObject[] mmsBodyArray = new JSONObject[length];
        String fileName = "";
        String signName = "";
        String smsChannelNumber = "";
        String name = new5gTemplateSyncBo.getTopic();
        List<UploadFileOrderBo> list = new5gTemplateSyncBo.getUploadFileOrderBo();
        List<UploadFileInfo> list2 = new ArrayList<>();
        String modeId = "";
        String sign = "";
        String ts = "";
        int order = 0;
        String type = "";
        String content = "";
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf2.format(new Date());
        try {
            //先变更多媒体模板顺序
            for(UploadFileOrderBo uploadFileOrderBo : list){
                order = uploadFileOrderBo.getOrderId();
                fileName = uploadFileOrderBo.getFileName();
                type = uploadFileOrderBo.getType();
                content = uploadFileOrderBo.getContent();
                //文本为新增，文件为变更
                if("1".equals(type)){
                    CreateUploadRecordBo createUploadRecordBo = new CreateUploadRecordBo();
                    createUploadRecordBo.setMgrId(mgrId);
                    createUploadRecordBo.setType(type);
                    createUploadRecordBo.setOrder(String.valueOf(order));
                    createUploadRecordBo.setFileName(mgrId+"_"+date+".txt");
                    createUploadRecordBo.setContent(content);
                    sms5gTemplateMapper.createUploadRecord(createUploadRecordBo);
                }else{
                    log.info("-----"+mgrId+"----"+"fileName");
                    sms5gTemplateMapper.update5gTemplateOrder(mgrId,fileName,order);
                }
            }
            list2 = sms5gTemplateMapper.qryUploadFileInfoList(mgrId);
            signName = sms5gSignatureMapper.qrySignatureNameById(signId);
            smsChannelNumber = sms5gSignatureMapper.qryChannelNumberBySignId(signId);
            //用于第一帧文字模板加上签名
            Boolean firstText = true;
            for(UploadFileInfo fileInfo : list2){

                type = fileInfo.getType();
                JSONObject templateJson = new JSONObject();
                order  = fileInfo.getOrderId();
                switch (type){
                    case "1" :
                        type = "text";
                        break;
                    case "2" :
                        type = "image";
                        break;
                    case "3" :
                        type = "video";
                        break;
                    case "4":
                        type = "audio";
                        break;
                }
                if("text".equals(type)){
                    templateJson.put("type",type);
                    templateJson.put("extType","txt");
                    if(firstText){
                        templateJson.put("body","【"+signName+"】"+fileInfo.getContent());
                        firstText = false;
                    }else{
                        templateJson.put("body",fileInfo.getContent());
                    }
                }else if("image".equals(type)||"video".equals(type)||"audio".equals(type)){
                    fileName = fileInfo.getFileName();
                    File file = new File(GlobalConst.MULTI_FILE_PATH+fileName);
                    InputStream inputStream  = new FileInputStream(file);
                    byte[] data =new byte[inputStream.available()];
                    inputStream.read(data);
                    inputStream.close();
                    String fileBase64String = Base64Utils.encodeToString(data);

                    int dotIndex = fileName.indexOf(".");
                    String extType = fileName.substring(dotIndex+1,fileName.length());

                    templateJson.put("type",type);
                    templateJson.put("extType",extType);
                    templateJson.put("bodyType","0");
                    templateJson.put("body",fileBase64String);
                }
                mmsBodyArray[order] = templateJson;
            }

            contentJson.put("subject",name);
            contentJson.put("mmsbody",mmsBodyArray);

            String contentJsonString = JSON.toJSONString(contentJson);
            Date nowDate = new Date();
            //时间戳精确到秒
            ts = String.valueOf(nowDate.getTime()/1000);
            sign = ts + GlobalConstants.SMS_5G_APP_KEY + GlobalConstants.SMS_5G_APP_SECRET;
            //sign = name + contentJsonString + ts + GlobalConstants.SMS_5G_APP_KEY + GlobalConstants.SMS_5G_APP_SECRET;
            //进行urlencode加密
            sign = URLEncoder.encode(sign,"UTF-8");
            //md5加密
            MD5 md5 = new MD5();
            sign = md5.getMD5ofStr(sign);
            sign = sign.toLowerCase();

            req.put("content",contentJsonString);

            req.put("appKey", GlobalConstants.SMS_5G_APP_KEY);
            req.put("name",name);
//            req.put("notifyUrl","");
//            req.put("pushOther","");
//            req.put("isTiled","");
            req.put("vsmsCode",smsChannelNumber);

            req.put("ts", ts);
            req.put("sign",sign);


            System.out.println("----"+req.toJSONString());

            String resp = CommonService.httpPostWithJson(GlobalConstants.SMS_5G_ADD_MODE_URL,req);
            System.out.println("----"+resp);
            //String resp = "1";
            if (!StringUtils.isEmpty(resp)) {
                //解压
                //resp = GZipUtil.gunzip(resp);
                log.info("newTemplateSync interface response:" + resp);
                //resp = "{\"code\":\"0\",\"msg\":\"\",\"rets\":{\"modeId\":\"1257034\"}}";
                JSONObject respJson = JSONObject.parseObject(resp);
                NewTemplateSyncResp newTemplateSyncResp = JSONObject.toJavaObject(respJson, NewTemplateSyncResp.class);
                String resultCode = newTemplateSyncResp.getCode();
                if (GlobalConstants.SUCCESS_STRING.equals(resultCode)) {
                    baseResult.setRetCode(GlobalConstants.SUCCESS_STRING);
                    Rets rets = newTemplateSyncResp.getRets();
                    modeId = rets.getModeId();
                }
                baseResult.setRetMsg(respJson.getString("msg"));
                //此处预留项目与modeId关联关系
                int updateResult = sms5gTemplateMapper.updateMgrModeId(mgrId,modeId);
                //变更项目审核状态
                if(updateResult>0){
                    Map<String, Object> mapState = new HashMap();
                    mapState.put("mgrId", mgrId);
                    mapState.put("state", "0");
                    smsTemplateCheckMapper.modifyTemplateStatus(mapState);
                }

                baseResult.setRetCode(GlobalConstants.SUCCESS_STRING);
                baseResult.setRetMsg("5g多媒体模板新增同步成功");
            }

        }catch (Exception e){
            e.printStackTrace();
            baseResult.setRetCode(GlobalConstants.EXCEPTION_STRING);
            baseResult.setRetMsg("5g多媒体模板新增同步出现异常");
        }
        return baseResult;
    }
    
    /**
     * @desc 查询5g多媒体模板
     * @param mgrId 
     * @return com.nl.controller.common.util.BaseResult
     * @author l
     * @date 2021/6/11 10:54
     */
    @Override
    public BaseResult qry5GTemplateInfo(String mgrId) {
        BaseResult baseResult = BaseResult.newFailInstance();
        Sms5gTemplateInfo sms5gTemplateInfo = new Sms5gTemplateInfo();
        List<UploadFileInfo> uploadFileInfo = new ArrayList<>();
        long allFileSize = 0;

        try {
            sms5gTemplateInfo = sms5gTemplateMapper.qry5gTemplateInfo(mgrId);
//            if(StringUtils.isEmpty(sms5gTemplateInfo.getIsNull())){
//                sms5gTemplateInfo.setIsNull("1");
//            }else{
//                sms5gTemplateInfo.setIsNull("0");
//            }
            uploadFileInfo = sms5gTemplateMapper.qryUploadFileInfoList(mgrId);
            if(!CollectionUtils.isEmpty(uploadFileInfo)){
                for(UploadFileInfo uploadFileInfo1:uploadFileInfo){
                    String type = uploadFileInfo1.getType();
                    if("1".equals(type)){
                        allFileSize++;
                    }else{
                        File file = new File(GlobalConst.MULTI_FILE_PATH+uploadFileInfo1.getFileName());
                        if(file.exists()){
                            long bytes = 0;
                            long kilobytes = 0;
                            bytes = file.length();
                            kilobytes = (bytes / 1024);
                            allFileSize= allFileSize+kilobytes;
                        }
                    }
                }
            }

            if(!Objects.isNull(sms5gTemplateInfo)){
                sms5gTemplateInfo.setUploadFileInfoList(uploadFileInfo);
                sms5gTemplateInfo.setAllFileSize(allFileSize+"");
            }
            baseResult.setRetCode(GlobalConstants.SUCCESS_STRING);
            baseResult.setRetMsg("查询5g多媒体模板成功");
            baseResult.setData(sms5gTemplateInfo);
        }catch (Exception e){
            e.printStackTrace();
            baseResult.setRetCode(GlobalConstants.EXCEPTION_STRING);
            baseResult.setRetMsg("查询5g多媒体模板出现异常");
        }
        return baseResult;
    }

    
    /**
     * aa
     * @desc 变更5g多媒体消息
     * @param update5gTemplateSyncBo 
     * @return com.nl.controller.common.util.BaseResult
     * @author l
     * @date 2021/6/11 11:01
     */
    @Override
    public BaseResult updateTemplateSync(Update5gTemplateSyncBo update5gTemplateSyncBo) {

        BaseResult baseResult = BaseResult.newFailInstance();
        //获取模板帧数
        int length = update5gTemplateSyncBo.getUploadFileOrderBo().size();

        JSONObject req = new JSONObject();
        JSONObject contentJson = new JSONObject();
        JSONObject[] mmsBodyArray = new JSONObject[length];
        String mgrId = update5gTemplateSyncBo.getMgrId();
        String fileName = "";
        String signId = update5gTemplateSyncBo.getSignId();
        String signName = "";
        String name = update5gTemplateSyncBo.getTopic();

        UpdateMgrSignRelBo updateMgrSignRelBo = new UpdateMgrSignRelBo();
        updateMgrSignRelBo.setMgrId(mgrId);
        updateMgrSignRelBo.setSignId(signId);
        updateMgrSignRelBo.setTopic(name);
        sms5gTemplateMapper.updateMgrSignRel(updateMgrSignRelBo);

        SignatureInfo signatureInfo = sms5gSignatureMapper.qrySignatureInfoById(signId);
        String openAccout = signatureInfo.getOpenAccount();
        String isArrearage = signatureInfo.getIsArrearage();
        //根据签名变更项目开户以及欠费状态
        if("0".equals(openAccout)){
            //签名未开户，项目也置为已开户
            openAccout = "-1";
        }
        smsBusiMapper.updateOpenAccoutIsArrearage(openAccout,isArrearage,mgrId);

        List<UploadFileOrderBo> list = update5gTemplateSyncBo.getUploadFileOrderBo();
        List<UploadFileInfo> list2 = new ArrayList<>();
        String modeId = update5gTemplateSyncBo.getModeId();
        String ts = "";
        String sign = "";

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf2.format(new Date());

        try {
            //先删除上传记录
            sms5gTemplateMapper.deleteUploadRecord(mgrId,"");
            //再插入记录
            for(UploadFileOrderBo uploadFileOrderBo : list){
                int order = uploadFileOrderBo.getOrderId();
                fileName = uploadFileOrderBo.getFileName();
                String type = uploadFileOrderBo.getType();
                String flag = uploadFileOrderBo.getFlag();
                CreateUploadRecordBo createUploadRecordBo = new CreateUploadRecordBo();
                String content = uploadFileOrderBo.getContent();
                createUploadRecordBo.setMgrId(mgrId);
                createUploadRecordBo.setType(type);
                createUploadRecordBo.setOrder(String.valueOf(order));
                if("1".equals(type)){
                    createUploadRecordBo.setFileName(mgrId+"_"+date+".txt");
                    createUploadRecordBo.setContent(content);
                }else{
                    createUploadRecordBo.setFileName(fileName);
                }
                sms5gTemplateMapper.createUploadRecord(createUploadRecordBo);
            }
            list2 = sms5gTemplateMapper.qryUploadFileInfoList(mgrId);
            log.info("==="+list2.toString());
            signName = sms5gSignatureMapper.qrySignatureNameById(signId);

            Boolean firstText = true;
            for(UploadFileInfo fileInfo : list2){
                String type = fileInfo.getType();
                JSONObject templateJson = new JSONObject();
                int order  = fileInfo.getOrderId();

                switch (type){
                    case "1" :
                        type = "text";
                        break;
                    case "2" :
                        type = "image";
                        break;
                    case "3" :
                        type = "video";
                        break;
                    case "4":
                        type = "audio";
                        break;
                }

                if("text".equals(type)){
                    templateJson.put("type",type);
                    templateJson.put("extType","txt");
                    if(firstText){
                        templateJson.put("body","【"+signName+"】"+fileInfo.getContent());
                        firstText = false;
                    }else{
                        templateJson.put("body",fileInfo.getContent());
                    }
                    //templateJson.put("body","【"+signName+"】"+fileInfo.getContent());
                    //templateJson.put("body",fileInfo.getContent());
                }else if("image".equals(type)||"video".equals(type)||"audio".equals(type)){
                    fileName = fileInfo.getFileName();
                    File file = new File(GlobalConst.MULTI_FILE_PATH+fileName);
                    InputStream inputStream  = new FileInputStream(file);
                    byte[] data =new byte[inputStream.available()];
                    inputStream.read(data);
                    inputStream.close();
                    String fileBase64String = Base64Utils.encodeToString(data);

                    int dotIndex = fileName.indexOf(".");
                    String extType = fileName.substring(dotIndex+1,fileName.length());
                    templateJson.put("type",type);
                    templateJson.put("extType",extType);
                    templateJson.put("bodyType","0");
                    templateJson.put("body",fileBase64String);
                }
                mmsBodyArray[order] = templateJson;
            }

            contentJson.put("subject",name);
            contentJson.put("mmsbody",mmsBodyArray);



            String contentJsonString = JSON.toJSONString(contentJson);

            Date nowDate = new Date();
            //时间戳精确到秒
            ts = String.valueOf(nowDate.getTime()/1000);

            sign = modeId + ts + GlobalConstants.SMS_5G_APP_KEY + GlobalConstants.SMS_5G_APP_SECRET;
            //进行urlencode加密
            sign = URLEncoder.encode(sign,"UTF-8");
            //md5加密
            MD5 md5 = new MD5();
            sign = md5.getMD5ofStr(sign);
            sign = sign.toLowerCase();
            req.put("content",contentJsonString);

            req.put("appKey", GlobalConstants.SMS_5G_APP_KEY);
            req.put("name",name);
            req.put("modeId",modeId);
//            req.put("notifyUrl","");
//            req.put("pushOther","");
//            req.put("isTiled","");

            req.put("ts",ts);
            req.put("sign",sign);
            log.info("modifyTemplateSync interface request:" + req.toJSONString());
            //String resp = "1";
            String resp = CommonService.httpPostWithJson(GlobalConstants.SMS_5G_UPDATE_MODE_URL,req);
            //String resp = "1";
            log.info("modifyTemplateSync interface response:" + resp);

            if (!StringUtils.isEmpty(resp)) {
                JSONObject respJson = JSONObject.parseObject(resp);
                NewTemplateSyncResp newTemplateSyncResp = JSONObject.toJavaObject(respJson, NewTemplateSyncResp.class);
                String resultCode = newTemplateSyncResp.getCode();
                if (GlobalConstants.SUCCESS_STRING.equals(resultCode)) {
                    baseResult.setRetCode(GlobalConstants.SUCCESS_STRING);
//                    Rets rets = newTemplateSyncResp.getRets();
//                    modeId = rets.getModeId();
                }
                baseResult.setRetMsg(respJson.getString("msg"));
                //变更项目审核状态
                Map<String, Object> mapState = new HashMap();
                mapState.put("mgrId", mgrId);
                mapState.put("state", "0");
                smsTemplateCheckMapper.modifyTemplateStatus(mapState);
                baseResult.setRetCode(GlobalConstants.SUCCESS_STRING);
                baseResult.setRetMsg("5g多媒体模板修改同步成功");
            }else {

            }

        }catch (Exception e){
            e.printStackTrace();
            baseResult.setRetCode(GlobalConstants.EXCEPTION_STRING);
            baseResult.setRetMsg("5g多媒体模板修改同步出现异常");
        }
        return baseResult;
    }
    
    /**
     * @desc 新增5G多媒体项目发送范围
     * @param createSendRangeBo
     * @return com.nl.controller.common.util.BaseResult
     * @author l
     * @date 2021/6/17 16:44
     */
    @Override
    public BaseResult createSendRange(CreateSendRangeBo createSendRangeBo) {
        BaseResult baseResult = BaseResult.newFailInstance();
        try {
            int insertResult = sms5gTemplateMapper.createSendRange(createSendRangeBo);
            baseResult.setRetCode(GlobalConstants.SUCCESS_STRING);
            baseResult.setRetMsg("新增5G项目发送范围成功");
        }catch (Exception e){
            e.printStackTrace();
            baseResult.setRetCode(GlobalConstants.EXCEPTION_STRING);
            baseResult.setRetMsg("新增5G项目发送范围发生异常");
        }
        return baseResult;
    }

    public static void main(String[] args) {
        try {
            Date nowDate = new Date();
            String ts = "";
            String sign = "";
            //时间戳精确到秒
            ts = String.valueOf(nowDate.getTime()/1000);
            sign = "438958"+ts + GlobalConstants.SMS_5G_APP_KEY + GlobalConstants.SMS_5G_APP_SECRET;
            //sign = name + contentJsonString + ts + GlobalConstants.SMS_5G_APP_KEY + GlobalConstants.SMS_5G_APP_SECRET;
            //进行urlencode加密
            sign = URLEncoder.encode(sign,"UTF-8");
            //md5加密
            MD5 md5 = new MD5();
            sign = md5.getMD5ofStr(sign);
            sign = sign.toLowerCase();
            System.out.println("---"+ts+"----"+sign);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
